package com.ajavaer.framework.common.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.function.Function;

@Component
public class SpringContext implements ApplicationContextAware {
    private static Logger log = LoggerFactory.getLogger(SpringContext.class);

    private static ApplicationContext applicationContext;
    private static PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();


    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("spring configuration failed");
        }
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz);
    }

    public static Resource getResource(String path) {
        try {
            Resource[] resources = pathMatchingResourcePatternResolver.getResources(path);
            if (resources.length > 0) {
                return resources[0];
            }
        } catch (IOException e) {
            log.error("file {} can not be found", log, e);
        }
        return null;
    }

    public static <T> T getIfPresent(Class<T> tClass) {
        try {
            return SpringContext.getBean(tClass);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T get(Class<T> tClass, Function<Class<T>, T> fun) {
        try {
            return SpringContext.getBean(tClass);
        } catch (Exception e) {
            return fun.apply(tClass);
        }
    }

    public static Environment env() {
        return applicationContext.getEnvironment();
    }

    public static boolean ready() {
        return applicationContext != null;
    }

    public static void setContext(ApplicationContext context) {
        applicationContext = context;
    }

}